package com.cheyunkeji.er.activity.fast_evaluate;

import android.Manifest;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.print.PrintAttributes;
import android.print.PrintManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.adapter.MyPrintAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.PushListEvaluater;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.DownloadUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.EasyPermissions;

import static com.cheyunkeji.er.utils.version.UpdatePresenter.WRITE_EXTERNAL_STORAGE;

public class FastEvaluateReportActivity extends BaseActivity
    implements SDialog.SDialog2Listener, UMShareListener {

  private static final String TAG = FastEvaluateReportActivity.class.getSimpleName();

  @BindView(R.id.tv_push)
  TextView tvPush;

  @BindView(R.id.tv_build_sj)
  TextView tvBuildSj;

  @BindView(R.id.ll_bottom)
  LinearLayout llBottom;

  @BindView(R.id.v_topbar)
  TopBar vTopbar;
  //    @BindView(R.id.wv_container)
  //    WebView wvContainer;
  @BindView(R.id.ll_webview)
  LinearLayout ll_webview;

  @BindView(R.id.activity_fast_evaluate_report)
  RelativeLayout activityFastEvaluateReport;

  //    keyword :
  // 长度为6的String数组，第一个为h5地址，第二个为pid，第三个为push_type(同步建立销售商机)，第四个为push_archive_type（推送至全面评估）
  //   h5, pid, push_type, push_archive_type,spec_name,data.optString("zqb")

  private String[] data = null;
  private Spinner spinner;
  private TextView cancel;
  private TextView confirm;

  private AlertDialog alertDialog;
  private List<String> spinnerList;
  private int spinnerSelect = 0;
  private PushListEvaluater pushListEvaluater;
  private SDialog dialog;
  private boolean sms = false, pushBoolean = false;
  private ShareAction mShareAction;

  @Override
  public void onStart(SHARE_MEDIA platform) {}

  @Override
  public void onResult(SHARE_MEDIA platform) {
    SToast.show("分享成功");
  }

  @Override
  public void onError(SHARE_MEDIA platform, Throwable t) {
    SToast.show("分享失败");
  }

  @Override
  public void onCancel(SHARE_MEDIA platform) {
    SToast.show("分享取消了");
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    /** attention to this below ,must add this* */
    UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
  }

  /** 屏幕横竖屏切换时避免出现window leak的问题 */
  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mShareAction.close();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    UMShareAPI.get(this).release();
  }

  @Override
  protected void init() {

    setContentView(R.layout.er_activity_fast_evaluate_report);
    ButterKnife.bind(this);

    /*增加自定义按钮的分享面板*/
    mShareAction =
        new ShareAction(this)
            .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .addButton("复制链接","copy_link","copy_link","copy_link")
            .setShareboardclickCallback(
                new ShareBoardlistener() {
                  @Override
                  public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                    if(share_media  == null) {
                      if (snsPlatform.mKeyword.equals("copy_link")) {
                        ClipboardManager cmb = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
                        cmb.setText(data[0]);
                        SToast.show("复制链接成功", Gravity.CENTER);
                      }
                    }else{
                      SToast.show("暂未开放", Gravity.CENTER);
//                      UMWeb web = new UMWeb(data[0]);
//                      web.setTitle("估价报告");
//                      web.setDescription(data[4]);
//                      UMImage umImage;
//                      if (TextUtils.isEmpty(data[5])) {
//                        umImage = new UMImage(FastEvaluateReportActivity.this, R.drawable.logo);
//                      } else {
//                        //                            umImage = new
//                        // UMImage(FastEvaluateReportActivity.this,data[5]);
//                        umImage = new UMImage(FastEvaluateReportActivity.this, R.drawable.logo);
//                      }
//                      web.setThumb(umImage);
//                      new ShareAction(FastEvaluateReportActivity.this)
//                              .withMedia(web)
//                              .setPlatform(share_media)
//                              .setCallback(FastEvaluateReportActivity.this)
//                              .share();
                    }
                  }
                });
  }

  @Override
  protected void initView() {
    vTopbar.setTitle("估价报告");
    vTopbar.setLeftBack();
    vTopbar.setRight("打印", -1, this);
    vTopbar.vShare.setVisibility(View.VISIBLE);
    vTopbar.vShare.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            ShareBoardConfig config = new ShareBoardConfig();
            config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE);
            mShareAction.open(config);
          }
        });

    if (null != getIntent().getStringArrayExtra("data")) {
      data = getIntent().getStringArrayExtra("data");
      //            wvContainer.getSettings().setJavaScriptEnabled(true);
      //            wvContainer.getSettings().setBlockNetworkImage(false);
      //            wvContainer.setWebViewClient(new WebViewClient());
      //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      //
      // wvContainer.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
      //            wvContainer.loadUrl(data[0]);

      AgentWeb mAgentWeb =
          AgentWeb.with(this) // 传入Activity
              .setAgentWebParent(ll_webview, new LinearLayout.LayoutParams(-1, -1))
              .useDefaultIndicator()
              .createAgentWeb()
              .ready()
              .go(data[0]);

      mAgentWeb
          .getWebCreator()
          .getWebView()
          .setWebChromeClient(
              new WebChromeClient() {
                @Override
                public void onReceivedTitle(WebView view, String title) {
                  super.onReceivedTitle(view, title);
                }

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                  super.onProgressChanged(view, newProgress);
                  mAgentWeb.getIndicatorController().setProgress(newProgress);
                }
              });

      mAgentWeb.getAgentWebSettings().getWebSettings().setUseWideViewPort(true);
      mAgentWeb.getAgentWebSettings().getWebSettings().setLoadWithOverviewMode(true);
    }

    View view =
        LayoutInflater.from(FastEvaluateReportActivity.this)
            .inflate(R.layout.er_dialog_push_evaluater, null);
    spinner = (Spinner) view.findViewById(R.id.dialog_push_spinner);
    cancel = (TextView) view.findViewById(R.id.dialog_push_cancel);
    confirm = (TextView) view.findViewById(R.id.dialog_push_confirm);
    alertDialog = new AlertDialog.Builder(this, R.style.dialog_style_dim_3).setView(view).create();

    cancel.setOnClickListener(this);
    confirm.setOnClickListener(this);
    tvBuildSj.setOnClickListener(this);
    tvPush.setOnClickListener(this);
    spinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            spinnerSelect = position;
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });

    if (Integer.parseInt(data[2]) == 3 || Integer.parseInt(data[2]) == 4) {
      tvBuildSj.setEnabled(false);
    }
    if (Integer.parseInt(data[3]) == 3 || Integer.parseInt(data[3]) == 4) {
      tvPush.setEnabled(false);
    }
  }

  @Override
  protected void initData() {}

  @Override
  public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      case R.id.tv_push:
        if (Integer.parseInt(data[3]) == 1) {
          pushBoolean = true;
          spinnerList = new ArrayList<>();
          if (!TextUtils.isEmpty(data[1])) {
            doPostRequest(HttpConstants.FAST_EVALUATE_PUSHLIST, null, null);
          }
        } else if (Integer.parseInt(data[3]) == 2) {
          pushBoolean = true;
          dialog =
              new SDialog(
                  FastEvaluateReportActivity.this,
                  R.string.t_message_title,
                  "将该客户信息通过短信方式\n发送指定评估师",
                  FastEvaluateReportActivity.this,
                  SDialog.TYPE_2_BTN);
          dialog.show();
        }
        //                pushBoolean = true;
        //                spinnerList = new ArrayList<>();
        //                if (!TextUtils.isEmpty(data[1])) {
        //                    doPostRequest(HttpConstants.FAST_EVALUATE_PUSHLIST, null, null);
        //                }
        break;
      case R.id.tv_build_sj:
        pushBoolean = false;
        switch (Integer.parseInt(data[2])) {
          case 1:
            dialog =
                new SDialog(
                    this, R.string.t_message_title, "将改客户信息推送至销售", this, SDialog.TYPE_2_BTN);
            break;
          case 2:
            dialog =
                new SDialog(
                    this,
                    R.string.t_message_title,
                    "将该客户信息通过短信方式\n发送至指定销售顾问",
                    this,
                    SDialog.TYPE_2_BTN);
            break;
          case 3:
            dialog =
                new SDialog(
                    this, R.string.t_message_title, "该信息已推送过\n不能重复推送", this, SDialog.TYPE_2_BTN);
            break;
          case 4:
            dialog =
                new SDialog(
                    this,
                    R.string.t_message_title,
                    "您还未绑定系统或设置推送号码\n请联系通道管理员进行设置",
                    this,
                    SDialog.TYPE_2_BTN);
            break;
        }

        dialog.show();

        //                if (!TextUtils.isEmpty(data[1])) {
        //                    doPostRequest(HttpConstants.SYNCHRONIZE_BUILD_SJ, data[1],null);
        //                }

        break;

      case R.id.vRight:
        // 打印
        if (!TextUtils.isEmpty(data[1])) {
          String[] params = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
          if (EasyPermissions.hasPermissions(this, params)) {
            doPostRequest(HttpConstants.PRINT_EVALUATE_REPORT, data[1], null);
          } else {
            EasyPermissions.requestPermissions(this, "需要读写本地权限", WRITE_EXTERNAL_STORAGE, params);
          }
        }
        break;
      case R.id.dialog_push_cancel:
        alertDialog.dismiss();
        break;

      case R.id.dialog_push_confirm:
        if (!TextUtils.isEmpty(data[1]) && pushListEvaluater.getData().size() > 0) {
          doPostRequest(
              HttpConstants.FAST_EVALUATE_PUSH_TO_ENTIRE_EVALUATE,
              data[1],
              pushListEvaluater.getData().get(spinnerSelect).getUid());
        }
      default:
        break;
    }
  }

  public void doPostRequest(final String httpUrl, final String pid, final String rcuid) {

    HashMap<String, String> params = new HashMap<>();
    //        params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    //        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

    if (pid != null) {
      params.put("pid", pid);
    }
    if (rcuid != null) {
      params.put("rcuid", rcuid);
    }

    ApiClient.postForm(
        httpUrl,
        params,
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {

            SToast.show("请求失败");
          }

          @Override
          public void onResponse(String response, int id) {
            Log.e("===" + TAG, httpUrl + "===" + response);
            //                if (dialog!=null&&dialog.isShowing()){
            //                    Log.e(TAG+"Dialog", "onResponse: " +
            // (dialog!=null)+"==="+(dialog.isShowing()));
            //                    pushBoolean = false;
            //                    dialog.dismiss();
            //                }
            if (rcuid != null) {
              Log.e(TAG + "Rcuid", "onResponse: " + response);
              try {
                alertDialog.dismiss();
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.getInt("code") == 1) {
                  SToast.show("推送成功");
                  tvPush.setEnabled(false);
                  sms = true;
                } else {
                  SToast.show("推送失败");
                }
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              Log.e(TAG + httpUrl, response + "=" + pushBoolean);
              if (pid != null) {
                JSONObject jsonObject = null;
                try {
                  jsonObject = new JSONObject(response);
                  if (jsonObject.getInt("code") == 1) {
                    if (jsonObject.getString("msg").length() > 0) {
                      SToast.show(new JSONObject(response).getString("msg"));
                    } else {
                      if (pushBoolean) {
                        tvPush.setEnabled(false);
                      } else {
                        tvBuildSj.setEnabled(false);
                      }
                      JSONObject data = jsonObject.getJSONObject("data");
                      if (data != null) {
                        String filePath = data.getString("filepath");
                        if (!filePath.isEmpty()) {
                          confirmPrint(filePath);
                        }
                      } else {
                        SToast.show("提交成功");
                      }
                    }
                  } else {
                    SToast.show(new JSONObject(response).getString("msg"));
                  }
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            }
            if (pid == null && rcuid == null) {
              Log.e(TAG + "NULL", "onResponse: " + response);
              pushListEvaluater = new Gson().fromJson(response, PushListEvaluater.class);
              if (pushListEvaluater.getData().size() > 0) {
                for (int i = 0; i < pushListEvaluater.getData().size(); i++) {
                  spinnerList.add(pushListEvaluater.getData().get(i).getRealname());
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<>(
                        FastEvaluateReportActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        spinnerList);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                TextView textView = new TextView(FastEvaluateReportActivity.this);
                textView.setText("无数据");
                spinner.setEmptyView(textView);
                spinner.setAdapter(adapter);
                alertDialog.show();
              } else {
                Log.e(TAG + "TRUE", "onResponse: " + response);
                dialog =
                    new SDialog(
                        FastEvaluateReportActivity.this,
                        R.string.t_message_title,
                        "将该客户信息通过短信方式\n发送指定评估师",
                        FastEvaluateReportActivity.this,
                        SDialog.TYPE_2_BTN);
                dialog.show();
              }
            }
          }

          @Override
          public void onBefore(Request request, int id) {
            super.onBefore(request, id);
            if (!httpUrl.equals(HttpConstants.PRINT_EVALUATE_REPORT)) showDialog();
          }

          @Override
          public void onAfter(int id) {
            super.onAfter(id);
            if (!httpUrl.equals(HttpConstants.PRINT_EVALUATE_REPORT)) dismissDialog();
          }
        });
  }

  private void confirmPrint(String url) {
    final String name = "评估报告";
    final Activity activity = this;
    DownloadUtil.get()
        .download(
            url,
            Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator
                + "Download",
            name + ".pdf",
            new DownloadUtil.OnDownloadListener() {
              @Override
              public void onDownloadSuccess(File file) {
                Log.v("DOWN", "下載成功,文件已存入手机内部存储设备根目录下Download文件夾中");
                PrintManager printManager =
                    (PrintManager) activity.getSystemService(Context.PRINT_SERVICE);
                PrintAttributes.Builder builder = new PrintAttributes.Builder();
                builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
                printManager.print(
                    name, new MyPrintAdapter(activity, file.getPath(), name), builder.build());
                Looper.prepare();
                Looper.loop();
              }

              @Override
              public void onDownloading(int progress) {
                Log.v("DOWN", "下載進度$progress");
              }

              @Override
              public void onDownloadFailed(Exception e) {
                Log.v("DOWN", e.toString());
              }
            });
  }

  @Override
  public void onClick(boolean l, View view) {
    Log.e(TAG + "ON", "dialog: " + l + "===" + pushBoolean);
    if (!l) {
      if (pushBoolean) {
        doPostRequest(HttpConstants.FAST_EVALUATE_PUSH_TO_ENTIRE_EVALUATE, data[1], null);
      } else {
        if (Integer.parseInt(data[2]) == 1 || Integer.parseInt(data[2]) == 2) {
          doPostRequest(HttpConstants.SYNCHRONIZE_BUILD_SJ, data[1], null);
        }
      }
    } else {
      SToast.show("取消");
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public void onStart() {
    super.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
  }
}
